﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WadViewer.DomainModel;
using WadViewer.Configuration;

namespace WadViewer.WinApp
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private WadViewer.DomainModel.WadRepository repository = new DomainModel.WadRepository();

		public MainWindow()
		{
			InitializeComponent();
			this.dpFrom.SelectedDate = DateTime.Now.Date.AddDays(-2);
			this.dpTo.SelectedDate = DateTime.Now.Date;

			this.cbConnections.ItemsSource = ConnectionManager.GetConnections();

			this.cbConnections.SelectionChanged += new SelectionChangedEventHandler(ConnectionSelectionChanged);
			this.cbTable.SelectionChanged += new SelectionChangedEventHandler(FilterSelectionChanged);
			this.dpFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(FilterSelectionChanged);
			this.dpTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(FilterSelectionChanged);
		}

		void ConnectionSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var connection = this.cbConnections.SelectedItem;
			this.repository.Setup(connection as TableConnection);
		}

		private void FilterSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (cbConnections.SelectedItem != null)
			{
				switch (cbTable.SelectedIndex)
				{
					case 0:
						ShowTraceLogs();
						break;
					case 1:
						ShowEventLogs();
						break;
					case 2:
						ShowPerfCounters();
						break;
				}
			}
		}

		private void ShowTraceLogs()
		{
			var traceLogs = repository.RetrieveTraceLogs(this.dpFrom.SelectedDate.Value, this.dpTo.SelectedDate.Value, 1000);
			this.icEntities.ItemsSource = traceLogs;
			this.tbCount.Content = traceLogs.Count;
			this.tbTimestamp.Content = DateTime.Now;
			this.tbStatus.Content = "Retrieved trace logs";
		}

		private void ShowEventLogs()
		{
			var eventLogs = repository.RetrieveEventLogs(this.dpFrom.SelectedDate.Value, this.dpTo.SelectedDate.Value, 1000);
			this.icEntities.ItemsSource = eventLogs;
			this.tbCount.Content = eventLogs.Count;
			this.tbTimestamp.Content = DateTime.Now;
			this.tbStatus.Content = "Retrieved event logs";
		}

		private void ShowPerfCounters()
		{
			var perfCounters = repository.RetrievePerfCounters(this.dpFrom.SelectedDate.Value, this.dpTo.SelectedDate.Value, 1000);
			this.icEntities.ItemsSource = perfCounters;
			this.tbCount.Content = perfCounters.Count;
			this.tbTimestamp.Content = DateTime.Now;
			this.tbStatus.Content = "Retrieved performance counters";
		}
	}
}
